/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package user;

/**
 *
 * @author Killian
 */
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import util.Utils;

public class UserAction extends ActionSupport implements ModelDriven<User> {

    private static final long serialVersionUID = 9149826260758390091L;
    private static final Logger logger = Logger.getLogger(UserAction.class);

    private int id_user;
    private String identifiant;
    private String mail;
    private String oldPassword;
    private String password;
    private String passwordConfirm;
    private List<User> listUser;
    private UserDAO userDao;
    private User user;
    private int id_droit;
    
    private static final String EMAIL_PATTERN = 
		"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public String execute() { 
        logger.info("------method execute");
        
        //Used to return the user to the form if there's a mistake there
        user = new User(id_user, identifiant, mail, password);
        if (validateForm()) {
            logger.info("Form OK");
            //Allow to emptcrypt the password to save in the DB
            //user.setPassword(Utils.encrypt(password, getText("key")));
            user.setPassword(password);
            user.setDroit(new Droit(id_droit));
            UserDAO userDao = new UserDAO();
            userDao.saveOrUpdateUser(user);
            addActionMessage("ok");
            return SUCCESS;
        } else {      
            logger.warn("Form NOK");
            return INPUT;
        }
    }

    public String getListUsers() {
        logger.info("------method getListUsers");
        userDao = new UserDAO();
        listUser = userDao.listUsers();
        return SUCCESS;
    }
    
    /**
     * Display the profil of the connected user
     * @return 
     */
    public String displayProfil() {
        logger.info("------method displayProfil");
        userDao = new UserDAO();
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        user = userDao.getUserById(Integer.parseInt(request.getParameter("id_user")));
        return SUCCESS;
    }
    
    /**
     * Display the page to update her profil
     * Recover informations about user connected
     * @return String
     */
    public String editProfil() {
        logger.info("------method editProfil");
        userDao = new UserDAO();
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        System.out.println("id: " + request.getParameter("id_user"));
        user = userDao.getUserById(Integer.parseInt(request.getParameter("id_user")));
        return SUCCESS;
    }
    
    public String editUser() {
        logger.info("------method editUser");
        userDao = new UserDAO();
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);     
        user = userDao.getUserById(Integer.parseInt(request.getParameter("id_user")));
        user.setIdentifiant(identifiant);
        user.setMail(mail);
        user.setDroit(new Droit(id_droit));
        userDao.saveOrUpdateUser(user);
        return SUCCESS;
    }

    public String changePassword() {
        logger.info("------method changePassword");
        userDao = new UserDAO();
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        
        //Used to return the user to the form if there's a mistake there
        user = userDao.getUserById(Integer.parseInt(request.getParameter("id_user")));
        //Call functon to check the old password is correct
        //if (userDao.checkPassword(Integer.parseInt(request.getParameter("id_user")), Utils.encrypt(oldPassword,getText("key")))) {
        if (userDao.checkPassword(Integer.parseInt(request.getParameter("id_user")), oldPassword)) {
            //Check if the new password is confirmed
            if (password.equals(passwordConfirm)) {
                logger.info("id: " + request.getParameter("id_user"));
                user = userDao.getUserById(Integer.parseInt(request.getParameter("id_user")));
                //user.setPassword(Utils.encrypt(password,getText("key")));
                user.setPassword(password);
                userDao.saveOrUpdateUser(user);
            }
            else {
                addFieldError("passwordConfirm", getText("error.passwordConfirm"));
            }
        }
        else {
            addFieldError("oldPassword", getText("error.oldPasswordIncorrect"));
        }
        return SUCCESS;
    }

    public String deleteUser() {
        logger.info("------method deleteUser");
        userDao = new UserDAO();
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        userDao.deleteUser(Integer.parseInt(request.getParameter("id_user")));
        listUser = userDao.listUsers();
        return SUCCESS;
    }

    static User getUserByIdentifiant(String identifiant) {
        UserDAO userDao = new UserDAO();
        User user = userDao.getUser(identifiant);
        return user;
    }

    public int getId_user() {
        return id_user;
    }

    public void setId_user(int id_user) {
        this.id_user = id_user;
    }

    public String getIdentifiant() {
        return identifiant;
    }

    public void setIdentifiant(String identifiant) {
        this.identifiant = identifiant;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<User> getListUser() {
        return listUser;
    }

    public void setListUser(List<User> listUser) {
        this.listUser = listUser;
    }

    public String getPasswordConfirm() {
        return passwordConfirm;
    }

    public void setPasswordConfirm(String passwordConfirm) {
        this.passwordConfirm = passwordConfirm;
    }

    public int getId_droit() {
        return id_droit;
    }

    public void setId_droit(int id_droit) {
        this.id_droit = id_droit;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    @Override
    public User getModel() {
        return user;
    }

    public boolean validateForm() {
        logger.info("-----method validateForm");
        boolean is_correct = true;
        if (identifiant.isEmpty()) {
            addFieldError("identifiant",getText("error.identifiant"));
            is_correct = false;
        } 
        if(identifiant.length() < 3 && !identifiant.isEmpty()) {
            addFieldError("identifiant",getText("error.lengthIdentifiant"));
            is_correct = false;
        }
        
        //We check if the login don't exist in the DB, users may have the same login if the case is different
        //The login must be different because it allows to connect
        userDao = new UserDAO();
        listUser = userDao.listUsers();
        List<String> listIdentifiant = new ArrayList<>();
        listUser.stream().forEach((User u) -> {
            listIdentifiant.add(u.getIdentifiant());
        });
        if(listIdentifiant.contains(identifiant)) {
            addFieldError("identifiant",getText("error.sameIdentifiant"));
            is_correct = false;
        }
        
        if(password.isEmpty()) {
            addFieldError("password",getText("error.password"));
            is_correct = false;
        }
        if(password.length() <= 5 && !password.isEmpty() && !passwordConfirm.isEmpty()) {
            addFieldError("password",getText("error.lengthPassword"));
            is_correct = false;
        }
        if(passwordConfirm.isEmpty()) {
            addFieldError("passwordConfirm",getText("error.passwordConfirm"));
            is_correct = false;
        }
        
        if(!password.equals(passwordConfirm) && !password.isEmpty() && !passwordConfirm.isEmpty()) {
            addFieldError("passwordConfirm",getText("error.passwordDifferent"));
            is_correct = false;
        }
        if(mail.isEmpty()) {
            addFieldError("mail",getText("error.mail"));
            is_correct = false;
        }
        else {
            //We check if mail format is correct
            Pattern pattern = Pattern.compile(EMAIL_PATTERN);
            if(!pattern.matcher(mail).matches()) {
                addFieldError("mail",getText("error.formatMail"));
                is_correct = false;
            }
        }
        return is_correct;
    }
}
